package com.arch.dev.server.interceptor;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

import com.arch.dev.server.bean.AbstractTimestampEntity;

class AuditTrailInterceptor extends EmptyInterceptor {
	

	public boolean onFlushDirty(Object entity, Serializable id,
			Object[] currentState, Object[] previousState,
			String[] propertyNames, org.hibernate.type.Type[] types) {		
		   if (entity instanceof AbstractTimestampEntity) {
	           // int indexOf = ArrayUtils.indexOf(propertyNames, "lastUpdated");
	           // currentState[indexOf] = new Date();
			   setValue(currentState, propertyNames, "lastUpdated", Calendar.getInstance().getTime());
	            return true;
	        }
	        return false;
	}
	
	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {
		  if (entity instanceof AbstractTimestampEntity) {
              //int indexOf = ArrayUtils.indexOf(propertyNames, "createdDate");
              //state[indexOf] = new Date();
			  
			  setValue(state, propertyNames, "createdDate", Calendar.getInstance().getTime());
			  setValue(state, propertyNames, "lastUpdated", Calendar.getInstance().getTime());
              return true;
          }
          return false;
	}
	
	private void setValue(Object[] currentState, String[] propertyNames,
			String propertyToSet, Object value) {
		int index = Arrays.asList(propertyNames).indexOf(propertyToSet);
		if (index >= 0) {
			currentState[index] = value;
		}
	}
	
}